package cn.sdstudio.controller;
import cn.sdstudio.model.PageResult;
import cn.sdstudio.model.Result;

import cn.sdstudio.entity.User;
import cn.sdstudio.entity.UserFavorite;
import cn.sdstudio.vo.FavoriteVO;
import cn.sdstudio.service.FavoriteService;
import cn.sdstudio.service.UserService;
import cn.sdstudio.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/favorites")
@RequiredArgsConstructor
public class FavoriteController {

    private final FavoriteService favoriteService;

    private final UserService userService;

    private final JwtUtils jwtUtil;

    @PostMapping("/add")
    public Result<FavoriteVO> addFavorite(@RequestParam Long scenicSpotId ,@RequestHeader String token) {
        Long userId = jwtUtil.getUserId(token);
        User user = userService.getById(userId);
        if(user == null){
            Result.error(403,"用户未登陆！");
        }

        UserFavorite userFavorite = new UserFavorite().setUserId(userId).setScenic_spot_id(scenicSpotId);
        boolean flag = favoriteService.save(userFavorite);
        if(flag){
            return Result.success(null);
        }
        return Result.error(400,"添加收藏失败");
    }
    @GetMapping("/list")
    public Result<PageResult<FavoriteVO>> listFavorites(@RequestParam(defaultValue = "1")
                                                        Integer page,
                                                        @RequestParam(defaultValue = "10")
                                                        Integer size,
                                                        @RequestHeader String token) {
        Long userId = jwtUtil.getUserId(token);
        Result<PageResult<FavoriteVO>> pageResultResult = favoriteService.listFavorites(userId, page, size);
        return pageResultResult;
    }

    @GetMapping("/cancel")
    public Result deleteFavorite(@RequestHeader String token, @RequestParam Long scenicSpotId) {
        Long userId = jwtUtil.getUserId(token);
       return favoriteService.deleteFavorites(userId, scenicSpotId);
    }
}
